@config.main("Variation") {
    <link rel="stylesheet" media="screen" href="@routes.Assets.versioned("mscroll/css/lz_index.css")">

    <div class="body-box">
        <div class="page-box">

            @config.subTitle("Variation")

            <div class="main-body">

                @components.navUlComponents(
                    Seq(("geneId", "Search By Gene ID", searchForm("Gene ID", "ids", "geneIdForm")),
                        ("range", "Search By Range", rangeForm),
                    ), "geneId")




                <div id="result" class="result">
                    <hr/>

                    <h5>Result:</h5>

                    <table class="table table-hover table-bordered" id="table" style="width: 100%;" data-advanced-sortable="true" data-pagination="true"
                    data-show-export="true" data-export-types="['excel','txt']" data-export-data-type="all" data-page-list="[10]"
                    >
                        <thead>
                            <tr>
                                <th data-field="geneid" data-sortable="true" data-search-type="text">Gene ID</th>
                                <th data-field="chr" data-sortable="true" data-search-type="text">Chr</th>
                                <th data-field="start" data-sortable="true" data-search-type="text">Start</th>
                                <th data-field="end" data-sortable="true" data-search-type="text">End</th>
                                <th data-field="strand" data-sortable="true" data-search-type="text">Strand</th>
                                <th data-field="snp" data-sortable="true" data-search-type="text">SNP Nums</th>
                                <th data-field="indel" data-sortable="true" data-search-type="text">Indel Nums</th>
                                <th data-field="sv" data-sortable="true" data-search-type="text">SV Nums</th>

                            </tr>
                        </thead>
                    </table>

                    <div id="distribution">

                    </div>

                    <div id="piePlot">

                    </div>

                </div>
            </div>
        </div>
    </div>
    <script src="@routes.Assets.versioned("mscroll/js/mscroll.js")" type="text/javascript"></script>

    <script src="@routes.Assets.versioned("Highcharts-9.0.1/highcharts.js")" type ="text/javascript"></script>
    <script src="@routes.Assets.versioned("Highcharts-9.0.1/highcharts-more.js")" type ="text/javascript"></script>
    <script src="@routes.Assets.versioned("Highcharts-9.0.1/modules/exporting.js")" type ="text/javascript"></script>
    <script src="@routes.Assets.versioned("Highcharts-9.0.1/modules/offline-exporting.js")" type ="text/javascript"></script>
    <script src="@routes.Assets.versioned("Highcharts-9.0.1/modules/data.js")" type ="text/javascript"></script>
    <script src="@routes.Assets.versioned("Highcharts-9.0.1/modules/heatmap.js")" type ="text/javascript"></script>
    <script>


            $(function () {
                $("#table").bootstrapTable();
                formValidation()
                getChr()
            })

            function getEg(name) {
                const chr = "ZMNO"
                let eg = chr === "XJDY" ? "MS.gene00001,MS.gene00002,MS.gene00003,MS.gene00004,MS.gene00005,MS.gene00006,MS.gene00007,MS.gene00008,MS.gene00009,MS.gene00010"
                        : chr === "ZMNO" ? "MsG0180000001.01,MsG0180000002.01,MsG0180000003.01,MsG0180000004.01,MsG0180000005.01,MsG0180000006.01,MsG0180000007.01,MsG0180000008.01,MsG0180000009.01,MsG0180000010.01"
                                : chr === "MSAE" ? "MsaG000001,MsaG000002,MsaG000003,MsaG000004,MsaG000005,MsaG000006,MsaG000007,MsaG000008,MsaG000009,MsaG000010"
                                        : chr === "MTRU" ? "Medtr1g004930.JCVIMt4.0v1,Medtr1g004940.JCVIMt4.0v1,Medtr1g004950.JCVIMt4.0v1,Medtr1g004960.JCVIMt4.0v1,Medtr1g004980.JCVIMt4.0v1,Medtr1g004990.JCVIMt4.0v1,Medtr1g006460.JCVIMt4.0v1,Medtr1g006490.JCVIMt4.0v1,Medtr1g006530.JCVIMt4.0v1,Medtr1g006540.JCVIMt4.0v1" : ""
                $(`#${name}ids`).val(eg)
            }

            function getStart() {
                $("#start").val("1")
            }

            function getEnd() {
                $("#end").val("200000")
            }

            function getChr() {
                let species = "ZMNO"
                $.post("/alfalfa/search/getChr?species=" + species, (data) => {
                    $("#chr").empty().select2({data: data})
                })
            }

            function Search(formId) {
                let form = $("#" + formId)
                let fv = form.data("formValidation");
                fv.validate();
                if (fv.isValid()) {
                    let index = MyTable.prototype.runningIcon();
                    $.ajax({
                        url: "/alfalfa/variation/getGeneVarData?formId=" + formId,
                        type: "post",
                        data: form.serialize(),
                        success: (data) => {

                            $("#table").bootstrapTable("load", data.table);

                            $("#distribution").empty()
                            addDistributionHtml(data.snpPlot)
                            $.each(data.snpPlot, (i, v) => {
                                if (v.valid !== "false") {
                                    let type = [{data: [v.len], pointWidth: 1, name: "Measure"}]
                                    $("#snp-table-" + i).bootstrapTable({data: v.snpData})
                                    $("#indel-table-" + i).bootstrapTable({data: v.indelData})
                                    $("#sv-table-" + i).bootstrapTable({data: v.svData})
                                    bullet_gene_stru(JSON.parse(v.check), type, JSON.parse(v.scatter), v.len, v.strand, v.name, i)
                                }
                            })
                            $("#piePlot").empty()

                            $.each(data.table,(i,v)=>{

                                let pieData = [{name:"SNP",y:v.snp},{name:"Indel",y:v.indel},{name:"SV",y:v.sv}]
                                pie(pieData,v.geneid,i)
                            })



                            let $result = $("#result")
                            $result.show();
                            layer.close(index)
                            let target_top = $result.offset().top ;
                            $("html,body").animate({scrollTop: target_top}, 800);
                        }
                    })
                }
            }

            function pie(data,name,index) {
                new Highcharts.chart('pie_' + index, {
                    chart: {
                        plotBackgroundColor: null,
                        plotBorderWidth: null,
                        plotShadow: false,
                        type: 'pie'
                    },
                    title: {
                        text: null
                    },
                    tooltip: {
                        pointFormat: '{series.name}: <b>{point.y}</b>'
                    },
                    credits: {
                        enabled: false
                    },
                    plotOptions: {
                        pie: {
                            allowPointSelect: true,
                            cursor: 'pointer',
                            colors:["#303030","#EE7600","#7CB5EC"],
                            dataLabels: {
                                enabled: true,
                                format: '<b>{point.name}</b>: {point.y} ',
                                style: {
                                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                                }
                            }
                        }
                    },
                    series: [{
                        name: 'Nums',
                        colorByPoint: true,
                        data: data
                    }]
                });
            }

            function addDistributionHtml(snpPlot) {

                let head = ``
                let body = ``
                $.each(snpPlot, (i, v) => {
                    if (snpPlot.valid !== "false") {

                        let active = ""
                        let active2 = ""
                        if (i === 0) {
                            active = "active"
                            active2 = "show active"
                        }
                        head += `
                           <li class="nav-item" role="presentation">
                                <a class="nav-link  ${active}" id="dis-${i}-tab" data-toggle="tab" href="#dis-${i}" role="tab" aria-controls="dis-${i}" aria-selected="true">${v.name}</a>
                           </li>`

                        body += `
                           <div class="tab-pane fade  ${active2} " id="dis-${i}" role="tabpanel" aria-labelledby="dis-${i}-tab">
<div id="pie_${i}" style="  height: 400px"></div>


                           <div id="export_pic_one_${i}" style="width: 1350px;
                            height: auto;
                            margin-top: 10px">
                            <img src="/assets/images/gene_2.svg" style="margin-left: 350px;
                            width: 45%">
                            <span id="export_${i}" class="fa fa-download"
                            style="float: right;
                                margin-right: 50px;
                                cursor: pointer;
                                color: #407F8A;" title="download as png"></span>
                            <div id="bullet_${i}" style="height: 45px;
                                width: 1300px;
                                margin-left: 15px"></div>
                            <div id="container_${i}" style="height: 100px;
                                width: 1300px;
                                margin-left: 15px"></div>
                        </div>
<div style="width: 1350px">
                        <ul class="nav nav-tabs" role="tablist">
                             <li class="nav-item" role="presentation">
                                <a class="nav-link active" id="snp-${i}-tab" data-toggle="tab" href="#snp-${i}" role="tab" aria-controls="snp-${i}" aria-selected="true">SNP Table</a>
                           </li>
                           <li class="nav-item" role="presentation">
                                <a class="nav-link" id="indel-${i}-tab" data-toggle="tab" href="#indel-${i}" role="tab" aria-controls="indel-${i}" aria-selected="true">Indel Table</a>
                           </li>
                           <li class="nav-item" role="presentation">
                                <a class="nav-link" id="sv-${i}-tab" data-toggle="tab" href="#sv-${i}" role="tab" aria-controls="sv-${i}" aria-selected="true">SV Table</a>
                           </li>
                        </ul>
                         <div class="tab-content">
                          <div class="tab-pane fade show active" id="snp-${i}" role="tabpanel" aria-labelledby="snp-${i}-tab">
                              <table class="table table-hover table-bordered" id="snp-table-${i}" style="width: 100%;" data-advanced-sortable="true" data-pagination="true"
    data-show-export="true" data-export-types="['excel','txt']" data-export-data-type="all" data-page-list="[10]"
    >
        <thead>
            <tr>

                <th data-field="0" data-sortable="true" data-search-type="text">located_region</th>
                <th data-field="1" data-sortable="true" data-search-type="text">Geneid</th>
                <th data-field="2" data-sortable="true" data-search-type="text">Chr</th>
                <th data-field="3" data-sortable="true" data-search-type="text">Start</th>
                <th data-field="4" data-sortable="true" data-search-type="text">Stop</th>
                <th data-field="5" data-sortable="true" data-search-type="text">Ref</th>
                <th data-field="6" data-sortable="true" data-search-type="text">Alt</th>
                <th data-field="7" data-sortable="true" data-search-type="text">Allele_frequency</th>
                <th data-field="8" data-sortable="true" data-search-type="text">QUAL</th>
                <th data-field="9" data-sortable="true" data-search-type="text">Depth</th>
            </tr>
        </thead>
    </table>

</div>
                          <div class="tab-pane fade" id="indel-${i}" role="tabpanel" aria-labelledby="indel-${i}-tab">
 <table class="table table-hover table-bordered" id="indel-table-${i}" style="width: 100%;" data-advanced-sortable="true" data-pagination="true"
    data-show-export="true" data-export-types="['excel','txt']" data-export-data-type="all" data-page-list="[10]"
    >
        <thead>
            <tr>
                <th data-field="0" data-sortable="true" data-search-type="text">located_region</th>
                <th data-field="1" data-sortable="true" data-search-type="text">Geneid</th>
                <th data-field="2" data-sortable="true" data-search-type="text">Chr</th>
                <th data-field="3" data-sortable="true" data-search-type="text">Start</th>
                <th data-field="4" data-sortable="true" data-search-type="text">Stop</th>
                <th data-field="5" data-sortable="true" data-search-type="text">Ref</th>
                <th data-field="6" data-sortable="true" data-search-type="text">Alt</th>
                <th data-field="7" data-sortable="true" data-search-type="text">Allele_frequency</th>
                <th data-field="8" data-sortable="true" data-search-type="text">QUAL</th>
                <th data-field="9" data-sortable="true" data-search-type="text">Depth</th>
            </tr>
        </thead>
    </table>

</div>
                          <div class="tab-pane fade" id="sv-${i}" role="tabpanel" aria-labelledby="sv-${i}-tab">
  <table class="table table-hover table-bordered" id="sv-table-${i}" style="width: 100%;" data-advanced-sortable="true" data-pagination="true"
    data-show-export="true" data-export-types="['excel','txt']" data-export-data-type="all" data-page-list="[10]"
    >
        <thead>
            <tr>
                <th data-field="0" data-sortable="true" data-search-type="text">located_region</th>
                <th data-field="1" data-sortable="true" data-search-type="text">Geneid</th>
                <th data-field="2" data-sortable="true" data-search-type="text">Chr</th>
                <th data-field="3" data-sortable="true" data-search-type="text">Start</th>
                <th data-field="4" data-sortable="true" data-search-type="text">Stop</th>
                <th data-field="5" data-sortable="true" data-search-type="text">Ref</th>
                <th data-field="6" data-sortable="true" data-search-type="text">Alt</th>
                <th data-field="7" data-sortable="true" data-search-type="text">Allele_frequency</th>
                <th data-field="8" data-sortable="true" data-search-type="text">QUAL</th>
                <th data-field="9" data-sortable="true" data-search-type="text">Depth</th>
            </tr>
        </thead>
    </table>

</div>


                         </div>
</div>

                            </div>`
                    }

                })

                let html = `<ul class="nav nav-tabs" role="tablist">${head}</ul>
                <div class="tab-content">${body} </div>`

                $("#distribution").html(html)

            }

            function formValidation() {
                let queryText = {
                    validators: {
                        notEmpty: {
                            message: 'This is not be empty!'
                        }
                    }
                }
                let integer = {
                    validators: {
                        notEmpty: {
                            message: 'Word size is required！'
                        },
                        integer: {
                            message: 'Word size must be intger！'
                        }
                    }
                }
                $('#geneIdForm').formValidation({
                    framework: 'bootstrap',
                    icon: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        ids: queryText
                    }
                });
                $('#rangeForm').formValidation({
                    framework: 'bootstrap',
                    icon: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        start: integer,
                        end: integer
                    }
                });

            }

            function heatmap(data) {
                Highcharts.chart('heatmap', {
                    credits: {
                        enabled: false
                    },
                    data: {
                        csv: data.csv,
                    },
                    exporting: {
                        buttons: {
                            contextButton: {
                                menuItems: ["downloadPNG", "downloadJPEG", "downloadPDF", "downloadSVG"]
                            }
                        }
                    },
                    chart: {
                        type: 'heatmap',
                        height: 800,
                        margin: [60, 10, 250, 150],
                        zoomType: 'xy'
                    },
                    title: {
                        text: "Expression level heatmap of gene cluster"
                    },
                    xAxis: {
                        categories: data.xAxis,
                        //  startOnTick: true,
                        labels: {
                            align: 'right',
                            rotation: -90,
                            style: {
                                fontSize: '12px',
                                fontFamily: 'Arial, sans-serif'
                            }
                        }
                    },
                    yAxis: {
                        categories: data.yAxis,
                        title: "Gene",
                        endOnTick: false,
                        gridLineWidth: 0,
                        minorGridLineWidth: 0,
                        // showLastLabel:true
                    },
                    colorAxis: {
                        stops: [
                            [0.1, '#355F8D  '],
                            [0.5, '#2CA981'],
                            [1, '#F1E628']
                        ],
                        /*            min: data.min,
                                    max: data.max,*/
                    },
                    legend: {
                        title: {
                            style: {
                                fontWeight: '1',
                                color: '#555',
                                fontSize: '12px'
                            },
                            text: 'Expression(log2(TPM+1))'
                        }
                    },
                    tooltip: {
                        formatter: function () {
                            return '<b>' + data.xAxis[this.point.x] + '</b><br/>' + '<b>Gene:</b>' +
                                    data.yAxis[this.point.y] + '<br><b>Expression(log2(TPM+1)): ' + this.point.value + '</b> '
                                     ;
                        }
                    },
                    series: [{
                        borderWidth: 1,
                        turboThreshold: Number.MAX_VALUE // #3404, remove after 4.0.5 release
                    }]
                });
            }

            function bullet_gene_stru(data, type, scatter, len, strand, geneid, index) {

                var start_temp_arr = []
                var end_temp_arr = []
                for (var ii = 0; ii < data.length; ii++) {
                    start_temp_arr.push(data[ii]['from'])
                    end_temp_arr.push(data[ii]['to'])
                }
                var start_fin = Math.min.apply(null, start_temp_arr)
                var end_fin = Math.max.apply(null, end_temp_arr)
                if (strand == '+') {
                    var plot_num = end_fin
                    var plot_text = '→'
                    var x = -4
                    var y = 22
                }
                if (strand == '-') {
                    var plot_num = start_fin
                    var plot_text = '←'
                    var x = -25
                    var y = 22
                }

                Highcharts.Renderer.prototype.symbols.line = function (x, y, width, height) {
                    return ['M', x, y + width / 2, 'L', x + height, y + width / 2]
                }
                Highcharts.setOptions({
                    chart: {
                        type: 'bar',
                        width: 1300
                    },
                    credits: {
                        enabled: false
                    },
                    exporting: {
                        enabled: false
                    },
                    title: {
                        text: ''
                    },
                    xAxis: {
                        tickLength: 0,
                        lineColor: '#0083B7',
                        lineWidth: 0,
                        labels: {
                            style: {
                                fontWeight: 'bold'
                            }
                        }
                    },
                    yAxis: {
                        min: 0,
                        minPadding: 0,
                        maxPadding: 0,
                        tickColor: '#ccc',
                        tickWidth: 1,
                        tickLength: 3,
                        gridLineWidth: 0,
                        endOnTick: true,
                        title: {
                            text: ''
                        },
                        labels: {
                            y: 10,
                            style: {
                                fontSize: '8px'
                            }
                        }
                    },
                    plotOptions: {
                        bar: {
                            color: '#333333',
                            shadow: false,
                            borderWidth: 0
                        }
                    }
                })
                var chart1 = new Highcharts.Chart({
                    chart: {
                        renderTo: 'bullet_' + index,
                        width: 1300,
                        marginLeft: 50,
                        marginRight: 50,
                        marginTop: 19,
                        marginBottom: -1
                    },
                    tooltip: {
                        enabled: false
                    },
                    legend: {
                        enabled: false
                    },
                    xAxis: {
                        text: {
                            title: ''
                        },
                        visible: false,
                        labels: {
                            enabled: false
                        }
                    },
                    yAxis: {
                        plotLines: [
                            {
                                value: plot_num,
                                width: 0,
                                color: 'black',
                                zIndex: 100,
                                label: {
                                    rotation: 0,
                                    align: 'bottom',
                                    x: x,
                                    y: y,
                                    style: {
                                        fontSize: '30px'
                                    },
                                    text: plot_text
                                }
                            }
                        ],
                        labels: {
                            enabled: false
                        },
                        endOnTick: false,
                        plotBands: data
                    },
                    series: type
                })
                var chart2 = new Highcharts.Chart({
                    chart: {
                        renderTo: 'container_' + index,
                        width: 1250,
                        marginBottom: 26,
                        marginTop: 10,
                        marginLeft: 50,
                        type: 'bubble',
                        zoomType: 'xy'
                    },
                    title: {
                        text: geneid,
                        y: 70,
                        style: {
                            fontSize: '14px'
                        }
                    },
                    credits: {
                        enabled: false
                    },
                    exporting: {
                        enabled: false
                    },
                    legend: {
                        enabled: false
                    },
                    xAxis: {
                        title: {
                            enabled: false,
                            text: ''
                        },
                        startOnTick: false,
                        endOnTick: false,
                        showLastLabel: true,
                        min: 1,
                        max: len,
                        visible: false
                    },
                    yAxis: {
                        visible: false,
                        min: 4,
                        max: 5
                    },
                    plotOptions: {
                        bubble: {
                            marker: {
                               // radius: 6,
                                symbol: 'triangle-down'
                            },
                            minSize: 10,
                            maxSize: 50,
                            tooltip: {
                                headerFormat: '',
                                pointFormat: '{point.name}'
                            }
                        },
                        series: {
                            cursor: 'pointer',
/*                            point: {
                                events: {
                                    click: function () {
                                        var str = this.options.name
                                        var arr = str.split('||')
                                        var temp = arr[0]
                                        var pos = temp.substr(4, temp.length)
                                    //    snp_pos_information(geneStructureGlobalChr, pos)
                                    }
                                }
                            }*/
                        }
                    },
                    series: scatter
                })
                Highcharts.getSVG = function (charts, options, callback) {
                    var svgArr = [],
                            top = 0,
                            width = 0,
                            addSVG = function (svgres) {
                                var svgWidth = +svgres.match(
                                                /^<svg[^>]*width\s*=\s*\"?(\d+)\"?[^>]*>/
                                        )[1],
                                        svgHeight = +svgres.match(
                                                /^<svg[^>]*height\s*=\s*\"?(\d+)\"?[^>]*>/
                                        )[1],
                                        svg = svgres.replace(
                                                '<svg',
                                                '<g transform="translate(0,' + top + ')" '
                                        )
                                svg = svg.replace('</svg>', '</g>')
                                top += svgHeight
                                width = Math.max(width, svgWidth)
                                svgArr.push(svg)
                            },
                            exportChart = function (i) {
                                if (i === charts.length) {
                                    return callback(
                                            '<svg height="' +
                                            top +
                                            '" width="' +
                                            width +
                                            '" version="1.1" xmlns="http://www.w3.org/2000/svg">' +
                                            svgArr.join('') +
                                            '</svg>'
                                    )
                                }
                                charts[i].getSVGForLocalExport(
                                        options,
                                        {},
                                        function () {
                                            console.log('Failed to get SVG')
                                        },
                                        function (svg) {
                                            addSVG(svg)
                                            return exportChart(i + 1) // Export next only when this SVG is received
                                        }
                                )
                            }
                    exportChart(0)
                }
                Highcharts.exportCharts = function (charts, options) {
                    options = Highcharts.merge(Highcharts.getOptions().exporting, options)
                    Highcharts.getSVG(charts, options, function (svg) {
                        Highcharts.downloadSVGLocal(svg, options, function () {
                            console.log('Failed to export on client side')
                        })
                    })
                }
                Highcharts.setOptions({
                    exporting: {
                        fallbackToExportServer: false
                    }
                })
                document.getElementById('export_' + index).addEventListener('click', () => {
                    Highcharts.exportCharts([chart1, chart2])
                })
            }
    </script>
}

@searchForm(title: String, name: String, formId: String) = {
    <form class="registration-form col-sm-12 my-form" id="@formId">


        <div class="col-sm-12 form-group my-position">
            <label class="col-sm-2 my-position-title">@title :</label>
            <div class="col-sm-9">
                <textarea class="form-control" type="text" rows="5" name="@name" id="@{
                    formId + name
                }"></textarea>
                <span  >
                    e.g.,&nbsp;<a href="####" onclick="getEg('@formId')"><em class="egCrics">Example</em></a></span>
            </div>
        </div>

        @components.button(formId)
    </form>
}

@rangeForm = {
    <form class="registration-form col-sm-12 my-form" id="rangeForm">


        @components.chr()

        <div class="col-sm-12 form-group my-position">
            <label class="col-sm-2 my-position-title">Start Position:</label>
            <div class="col-sm-4" style="text-align: left">
                <input class="form-control" name="start" id="start">
            </div>
            <div class="col-sm-4" style="line-height: 40px">
                <span >
                    e.g.,&nbsp;<a href="#" onclick="getStart()"><em class="egCrics">1</em></a></span>
            </div>

        </div>

        <div class="col-sm-12 form-group my-position">
            <label class="col-sm-2 my-position-title">End Position:</label>
            <div class="col-sm-4" style="text-align: left">
                <input class="form-control" name="end" id="end">
            </div>
            <div class="col-sm-4" style="line-height: 40px">
                <span  >
                    e.g.,&nbsp;<a href="#" onclick="getEnd()"><em class="egCrics">200000</em></a></span>
            </div>
        </div>

        @components.button("rangeForm")
    </form>
}

